﻿using Microsoft.Extensions.DependencyInjection;
using PmSoft;
using PmSoft.Exceptions;

namespace Modules.System.Flow
{
    [UseDI(ServiceLifetime.Scoped)]
    public class SysFlowService
    {
        private readonly SysFlowRepository sysFlowRepository;
        private readonly SysFlowEngineRepository sysFlowEngineRepository;

        public SysFlowService(SysFlowRepository sysFlowRepository, SysFlowEngineRepository sysFlowEngineRepository)
        {
            this.sysFlowRepository = sysFlowRepository;
            this.sysFlowEngineRepository = sysFlowEngineRepository;
        }

        public void CreateFlow(SysFlow flow)
        {
            if (sysFlowRepository.Exists(flow, null))
                throw new BusinessException($"编码:{flow.Code}已存在");
            sysFlowRepository.Insert(flow);
        }

        public void UpdateFlow(SysFlow flow)
        {
            if (sysFlowRepository.Exists(flow, flow.Id))
                throw new BusinessException($"编码:{flow.Code}已存在");
            sysFlowRepository.Update(flow);
        }

        public void DeleteFlow(int id)
        {
            sysFlowRepository.DeleteByEntityId(id);
        }

        public void DeleteFlows(IEnumerable<int> ids)
        {
            foreach (var id in ids)
            {
                DeleteFlow(id);
            }
        }

        public SysFlow? GetFlow(int id)
        {
            return sysFlowRepository.Get(id);
        }

        public IPagedList<SysFlow> GetFlows(FlowQuery query, int pageIndex, int pageSize)
        {
            return sysFlowRepository.GetFlows(query, pageIndex, pageSize);
        }

        public SysFlow? GetFlowByCode(string code)
        {
            return sysFlowRepository.GetFlowByCode(code);
        }
    }
}